package de.koller.transit.engine.brush;

import de.koller.aframe.plain.PlainRasterInt;
import de.koller.aframe.plain.Sprite;
import de.koller.aframe.util.misc.ColorOperations;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;

public class BrushRender {
	
	private final Brush brush;
	private Sprite spriteNormal = null;
	private float rot = 0;
	
	public BrushRender( Brush brush ) {
		this.brush = brush;
	}
	
	public void setup( GraphicsConfiguration gc, Sprite template ) {
		PlainRasterInt pre = new PlainRasterInt( template.width, template.height );
		for( int x = 0; x < pre.width; x++ )
			for( int y = 0; y < pre.height; y++ ) {
				pre.setPixel( template.raster.getColor( x, y ), x, y );
				if( template.raster.getColor( x, y ) == 0xff_ff0000 ) pre.setPixel( brush.color.get(), x, y );
				if( template.raster.getColor( x, y ) == 0xff_00ff00 ) pre.setPixel( brush.color.get(), x, y );
			}
		
		spriteNormal = reduceSprite( gc, pre );
		//ImagePreview.showImage( spriteNormal.image, template.width * 2, template.height * 2 );
	}
	
	public void renderThis( Graphics2D g, int elapsedTime ) {
		rot += brush.velocity.getValue() * 0.001;
		float r = (float)Math.sin( rot * 0.01f ) * .5f;
		float rd = (float)Math.cos( rot * 0.01f ) * .5f;
		//75 109
		
		AffineTransform a = new AffineTransform();
		a.translate( brush.position.getCurrent().x - 75/3, brush.position.getCurrent().y - 80 );
		if( rd < 0 ) {
			a.scale( -1, 1 );
			a.translate( -50, 0 );
			a.rotate( -r, 75/3, 109/3 );
		} else {
			a.rotate( r, 75/3, 109/3 );
		}
		
		g.drawImage( spriteNormal.image, a, null );
	}
	
	private Sprite reduceSprite( GraphicsConfiguration gc, PlainRasterInt tmp ) {
		Sprite s = new Sprite( gc.createCompatibleImage( tmp.width/ 3, tmp.height/ 3, Transparency.TRANSLUCENT ) );
		
		for( int x = 0; x < s.width; x++ )
			for( int y = 0; y < s.height; y++ ) {
				int[] rgb = new int[4];
				
				for( int ix = 0; ix < 3; ix++ )
					for( int iy = 0; iy < 3; iy++ ) {
						int[] trgb = ColorOperations.getColorComponents( tmp.getColor( x*3 + ix, y*3 + iy ) );
						for( int i = 0; i < 4; i++ ) rgb[i] += trgb[i];
					}
				
				for( int i = 0; i < 4; i++ ) rgb[i] /= 3*3;
				s.raster.setPixel( ColorOperations.getColorWithComponents( rgb ), x, y );
			}
		
		return s;
	}
	
}
